package com.mewp.permissions.common.utils;

import com.mewp.permissions.model.po.SysMenu;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据菜单数据构建菜单树的工具类
 *
 * @author mewp
 * @version 1.0
 * @date 2023/7/28 12:28
 */
public class MenuHelper {

    /**
     * 使用递归方法构建菜单
     *
     * @param sysMenuList 菜单列表
     * @return 树形结构菜单
     */
    public static List<SysMenu> buildMenu(List<SysMenu> sysMenuList) {
        List<SysMenu> trees = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if (sysMenu.getParentId() == 0) {
                SysMenu children = findChildren(sysMenu, sysMenuList);
                trees.add(children);
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param sysMenu   父节点
     * @param treeNodes 节点列表
     * @return 节点树
     */
    public static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> treeNodes) {
        sysMenu.setChildren(new ArrayList<>());

        for (SysMenu node : treeNodes) {
            if (sysMenu.getId().longValue() == node.getParentId().longValue()) {
                if (CollectionUtils.isEmpty(sysMenu.getChildren())) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                SysMenu children = findChildren(node, treeNodes);
                sysMenu.getChildren().add(children);
            }
        }
        return sysMenu;
    }
}
